// controllers/bannerController.js
const pool = require('../config/db');
const { sendResponse } = require('../utils/response');

// 获取所有轮播图（只返回启用状态的）
const getAllBanners = async (req, res) => {
  try {
    const [rows] = await pool.execute('SELECT * FROM banners WHERE status = 1 ORDER BY sort_order ASC');
    sendResponse(res, 200, '获取轮播图成功', rows);
  } catch (error) {
    sendResponse(res, 500, '获取轮播图失败', error.message);
  }
};

// 获取单个轮播图
const getBannerById = async (req, res) => {
  const { id } = req.params;
  try {
    const [rows] = await pool.execute('SELECT * FROM banners WHERE id = ?', [id]);
    if (rows.length === 0) {
      return sendResponse(res, 404, '轮播图未找到');
    }
    sendResponse(res, 200, '获取轮播图成功', rows[0]);
  } catch (error) {
    sendResponse(res, 500, '获取轮播图失败', error.message);
  }
};

// 创建轮播图（需要管理员权限）
const createBanner = async (req, res) => {
  const { title, link, sort_order, status } = req.body;
  // 获取上传的图片路径
  const image_url = req.file ? `/uploads/${req.file.filename}` : null;
  
  if (!image_url) {
    return sendResponse(res, 400, '请上传轮播图图片');
  }

  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();
    const [result] = await connection.execute(
      'INSERT INTO banners (title, image_url, link, sort_order, status) VALUES (?, ?, ?, ?, ?)',
      [title || '', image_url, link || '', sort_order || 0, status || 1]
    );
    await connection.commit();
    sendResponse(res, 201, '创建轮播图成功', { id: result.insertId });
  } catch (error) {
    await connection.rollback();
    sendResponse(res, 500, '创建轮播图失败', error.message);
  } finally {
    connection.release();
  }
};

// 更新轮播图（需要管理员权限）
const updateBanner = async (req, res) => {
  const { id } = req.params;
  const { title, link, sort_order, status } = req.body;
  // 获取上传的图片路径（如果有新图片上传）
  const image_url = req.file ? `/uploads/${req.file.filename}` : req.body.image_url;

  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();
    // 检查轮播图是否存在
    const [banners] = await connection.execute('SELECT * FROM banners WHERE id = ?', [id]);
    if (banners.length === 0) {
      await connection.rollback();
      return sendResponse(res, 404, '轮播图未找到');
    }

    const [result] = await connection.execute(
      'UPDATE banners SET title = ?, image_url = ?, link = ?, sort_order = ?, status = ? WHERE id = ?',
      [title || '', image_url, link || '', sort_order || 0, status || 1, id]
    );
    await connection.commit();
    sendResponse(res, 200, '更新轮播图成功');
  } catch (error) {
    await connection.rollback();
    sendResponse(res, 500, '更新轮播图失败', error.message);
  } finally {
    connection.release();
  }
};

// 删除轮播图（需要管理员权限）
const deleteBanner = async (req, res) => {
  const { id } = req.params;
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();
    // 检查轮播图是否存在
    const [banners] = await connection.execute('SELECT * FROM banners WHERE id = ?', [id]);
    if (banners.length === 0) {
      await connection.rollback();
      return sendResponse(res, 404, '轮播图未找到');
    }

    await connection.execute('DELETE FROM banners WHERE id = ?', [id]);
    await connection.commit();
    sendResponse(res, 200, '删除轮播图成功');
  } catch (error) {
    await connection.rollback();
    sendResponse(res, 500, '删除轮播图失败', error.message);
  } finally {
    connection.release();
  }
};

module.exports = {
  getAllBanners,
  getBannerById,
  createBanner,
  updateBanner,
  deleteBanner
};